﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using WpfHero;
using System.Windows.Media.Animation;

namespace WpfHeroTutorial
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public WHEngine Engine { get; set; }

        private Storyboard showLoading;
        private Storyboard startPlaying;
        private bool storyboardsInitialized = false;

        public Window1()
        {
            InitializeComponent();
            Engine = scroller.DataContext as WHEngine;
        }

        private void lbSongBrowser_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            SongBrowserDirSelected();
        }

        private void SongBrowserDirSelected()
        {
            SongBrowser sb = (SongBrowser) ((ObjectDataProvider) Resources["SongBrowserDS"]).ObjectInstance;
            var selectedDir = (MyDirectory) lbSongBrowser.SelectedItem;
            sb.CurrentDirectory = selectedDir;

            if (selectedDir.HasSong)
                StartGame(selectedDir.FullPath);
        }

        private void StartGame(string path)
        {
            Engine.Stop();

            if (!storyboardsInitialized)
            {
                showLoading.Completed += delegate
                                             {
                                                 Engine.Initialize(path, 1);
                                                 App.DoEvents();
                                                 startPlaying.Begin(this);
                                             };
                startPlaying.Completed += delegate
                                              {
                                                  scroller.Start();
                                                  Engine.Start();
                                              };
                storyboardsInitialized = true;
            }
            showLoading.Begin(this);
        }

        private void lbSongBrowser_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                SongBrowserDirSelected();
        }
    }
}
